<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class System extends CIC_A_Controller
{
	function __construct()
	{
		parent::__construct();
	}
	function site()
	{
		$this->admin_priv(__METHOD__);
		$data['site_config']	= $this->get_config('ciccms/site');
		$this->load->view('admin/system/site',$data);
	}
	
	function sys()
	{
		$this->admin_priv(__METHOD__);
		$data['sys_config'] =  $this->admin_config['sys'];
		$this->load->view('admin/system/sys',$data);
	}
	
	function update_sys_config()
	{
		$this->admin_priv(__METHOD__);
		if($this->input->post('submit'))
		{
			if(!empty($_FILES))
			{
				if($_FILES['water_image']['error']  != 4)
				{
					$_POST['water_path'] = $this->upload_water();
				}
			}
			
			if($this->write_config($this->input->post(), APPPATH.'config/ciccms/admin.php'))
			{
				$this->message->msg('操作成功！',site_url('admin/system/sys'));
			}else{
				$this->message->msg('操作失败！',site_url('admin/system/sys'));
			}
		}
	}
	
	function update_site_config()
	{
		$this->admin_priv(__METHOD__);
		if($this->input->post('submit'))
		{
			$this->config->set_item('global_xss_filtering', false);
			if($this->write_config($this->input->post(), APPPATH.'config/ciccms/site.php') && $this->write_config($this->input->post(), APPPATH.'config/config.php'))
			{
				$this->message->msg('操作成功！',site_url('admin/system/site'));
			}else{
				$this->message->msg('操作失败！',site_url('admin/system/site'));
			}
		}
	}
	
	private function upload_water()
	{
		$suffix = $this->get_suffix($_FILES['water_image']['name']);
		$config=array(
				'upload_path'		=> 'public/common/images/',
				'allowed_types'		=> 'gif|jpg|png',
				'file_name'			=> 'mark_water.'.$suffix,
				'overwrite'			=> TRUE,
				'remove_spaces'		=> TRUE,
		);
		$this->load->library('upload',$config);
		if($this->upload->do_upload('water_image'))
		{
			$upload_data = $this->upload->data();
			return $config['upload_path'].$config['file_name'];
		}else{
			$this->message->msg($this->upload->display_errors('<p>','</p>'),site_url('admin/system/sys'),100);
		}
	}
	
	private function write_config($data,$path)
	{
		$config = file_get_contents($path);
		foreach($data as $key => $value)
		{
			$pattern = '/\'('.$key.')\'(\s*)=>(\s*)\'(.*?)\'/is';
			$config = preg_replace($pattern, '\'\\1\'\\2=>\\3\''.$value.'\'', $config);
		}
		return file_put_contents($path,$config);
	}
	
	private function get_suffix($file_name)
	{
		return array_pop(explode('.', $file_name));
	}
}
